package com.vehiclemanagement.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vehiclemanagement.entity.Vehicle;
import com.vehiclemanagement.entity.VehicleUseRecord;
import com.vehiclemanagement.mapper.VehicleMapper;
import com.vehiclemanagement.mapper.VehicleUseRecordMapper;
import com.vehiclemanagement.service.VehicleUseRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 车辆出车记录服务实现类
 */
@Service
public class VehicleUseRecordServiceImpl extends ServiceImpl<VehicleUseRecordMapper, VehicleUseRecord> implements VehicleUseRecordService {

    @Autowired
    private VehicleUseRecordMapper vehicleUseRecordMapper;
    
    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public IPage<VehicleUseRecord> pageRecords(Integer current, Integer size, String searchTerm, 
                                             Long vehicleId, Long driverId, Integer status, 
                                             LocalDateTime startDate, LocalDateTime endDate) {
        // 创建分页对象
        Page<VehicleUseRecord> page = new Page<>(current, size);
        
        // 创建自定义SQL条件
        String whereSql = " r.del_flag = 0 ";
        
        // 添加搜索条件
        if (StringUtils.isNotBlank(searchTerm)) {
            whereSql += " AND (v.plate_number LIKE '%" + searchTerm + "%' OR d.name LIKE '%" + searchTerm + "%' " +
                    "OR r.purpose LIKE '%" + searchTerm + "%' OR r.destination LIKE '%" + searchTerm + "%') ";
        }
        
        // 添加车辆ID查询条件
        if (vehicleId != null) {
            whereSql += " AND r.vehicle_id = " + vehicleId;
        }
        
        // 添加驾驶员ID查询条件
        if (driverId != null) {
            whereSql += " AND r.driver_id = " + driverId;
        }
        
        // 添加状态查询条件
        if (status != null) {
            whereSql += " AND r.status = " + status;
        }
        
        // 添加时间范围查询条件
        if (startDate != null) {
            whereSql += " AND r.start_time >= '" + startDate + "'";
        }
        
        if (endDate != null) {
            whereSql += " AND r.start_time <= '" + endDate + "'";
        }
        
        // 添加排序
        whereSql += " ORDER BY r.create_time DESC";
        
        System.out.println("执行查询SQL条件: " + whereSql);
        
        // 执行查询
        return vehicleUseRecordMapper.selectPageWithInfo(page, whereSql);
    }

    @Override
    public VehicleUseRecord getRecordById(Long id) {
        return vehicleUseRecordMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addRecord(VehicleUseRecord record) {
        System.out.println("服务层开始添加出车记录: " + record);
        
        try {
            // 检查车辆是否可用
            if (hasActiveUseByVehicleId(record.getVehicleId())) {
                System.out.println("车辆已被使用，无法添加出车记录");
                return false;
            }
            
            // 检查驾驶员是否可用
            if (hasActiveUseByDriverId(record.getDriverId())) {
                System.out.println("驾驶员已被指派其他车辆，无法添加出车记录");
                return false;
            }
            
            // 设置默认值
            if (record.getCreateTime() == null) {
                record.setCreateTime(LocalDateTime.now());
            }
            if (record.getUpdateTime() == null) {
                record.setUpdateTime(LocalDateTime.now());
            }
            if (record.getDelFlag() == null) {
                record.setDelFlag(0);
            }
            if (record.getStatus() == null) {
                record.setStatus(0); // 默认未审批
            }
            
            // 执行插入
            int result = vehicleUseRecordMapper.insert(record);
            System.out.println("插入结果: " + result + ", 生成的ID: " + record.getId());
            
            return result > 0;
        } catch (Exception e) {
            System.err.println("添加出车记录发生异常: " + e.getMessage());
            e.printStackTrace();
            throw e; // 抛出异常以触发事务回滚
        }
    }

    @Override
    public boolean updateRecord(VehicleUseRecord record) {
        // 更新时间
        record.setUpdateTime(LocalDateTime.now());
        
        return vehicleUseRecordMapper.updateById(record) > 0;
    }

    @Override
    public boolean deleteRecord(Long id) {
        // 使用物理删除
        System.out.println("执行物理删除出车记录，ID: " + id);
        
        try {
            // 直接物理删除记录
            int result = vehicleUseRecordMapper.deletePhysically(id);
            System.out.println("物理删除结果: " + result);
            return result > 0;
        } catch (Exception e) {
            System.err.println("删除出车记录时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean approveRecord(Long id, String approver, boolean approved, String remark) {
        try {
            VehicleUseRecord record = vehicleUseRecordMapper.selectById(id);
            if (record == null) {
                System.out.println("出车记录不存在，ID: " + id);
                return false;
            }
            
            // 设置审批信息
            record.setApprover(approver);
            record.setStatus(approved ? 1 : 4); // 1-已审批，4-审批拒绝
            if (StringUtils.isNotBlank(remark)) {
                record.setRemark(remark);
            }
            record.setUpdateTime(LocalDateTime.now());
            
            int result = vehicleUseRecordMapper.updateById(record);
            
            // 如果审批通过，更新车辆状态为使用中
            if (approved && result > 0) {
                Vehicle vehicle = vehicleMapper.selectById(record.getVehicleId());
                if (vehicle != null) {
                    vehicle.setStatus(1); // 1-使用中
                    vehicle.setUpdateTime(LocalDateTime.now());
                    vehicleMapper.updateById(vehicle);
                    System.out.println("更新车辆状态为使用中，车辆ID: " + vehicle.getId());
                }
            }
            
            return result > 0;
        } catch (Exception e) {
            System.err.println("审批出车记录时出错: " + e.getMessage());
            e.printStackTrace();
            throw e; // 抛出异常以触发事务回滚
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean startUse(Long id, Double startMileage) {
        try {
            VehicleUseRecord record = vehicleUseRecordMapper.selectById(id);
            if (record == null) {
                System.out.println("出车记录不存在，ID: " + id);
                return false;
            }
            
            // 验证状态是否为已审批
            if (record.getStatus() != 1) {
                System.out.println("出车记录状态不是已审批，无法确认出车");
                return false;
            }
            
            // 设置出车信息
            record.setStartMileage(startMileage);
            record.setStartTime(LocalDateTime.now());
            record.setStatus(2); // 2-已出车
            record.setUpdateTime(LocalDateTime.now());
            
            // 更新出车记录
            return vehicleUseRecordMapper.updateById(record) > 0;
        } catch (Exception e) {
            System.err.println("确认出车时出错: " + e.getMessage());
            e.printStackTrace();
            throw e; // 抛出异常以触发事务回滚
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean returnVehicle(Long id, Double endMileage) {
        try {
            VehicleUseRecord record = vehicleUseRecordMapper.selectById(id);
            if (record == null) {
                System.out.println("出车记录不存在，ID: " + id);
                return false;
            }
            
            // 验证状态是否为已出车
            if (record.getStatus() != 2) {
                System.out.println("出车记录状态不是已出车，无法确认归还");
                return false;
            }
            
            // 验证归还里程数是否合法
            if (endMileage < record.getStartMileage()) {
                System.out.println("归还里程数不能小于出车里程数");
                return false;
            }
            
            LocalDateTime now = LocalDateTime.now();
            
            // 更新出车记录的归还信息
            int result = vehicleUseRecordMapper.updateReturnInfo(id, now, endMileage, now);
            
            if (result > 0) {
                // 更新车辆的当前里程数和状态
                Vehicle vehicle = vehicleMapper.selectById(record.getVehicleId());
                if (vehicle != null) {
                    vehicle.setCurrentMileage(endMileage);
                    vehicle.setStatus(0); // 0-空闲
                    vehicle.setUpdateTime(now);
                    vehicleMapper.updateById(vehicle);
                    System.out.println("更新车辆状态为空闲，车辆ID: " + vehicle.getId());
                }
            }
            
            return result > 0;
        } catch (Exception e) {
            System.err.println("确认归还时出错: " + e.getMessage());
            e.printStackTrace();
            throw e; // 抛出异常以触发事务回滚
        }
    }

    @Override
    public boolean hasActiveUseByVehicleId(Long vehicleId) {
        return vehicleUseRecordMapper.countActiveUseByVehicleId(vehicleId) > 0;
    }

    @Override
    public boolean hasActiveUseByDriverId(Long driverId) {
        return vehicleUseRecordMapper.countActiveUseByDriverId(driverId) > 0;
    }
} 